package com.sunshine.simplehospital.ui.activity

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.snackbar.Snackbar
import com.sunshine.simplehospital.R
import com.sunshine.simplehospital.base.BaseActivity
import com.sunshine.simplehospital.viewmodel.LoginViewModel
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : BaseActivity() {

    private lateinit var viewModel: LoginViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)

        supportActionBar?.title = "登录简医"

        register.setOnClickListener {
            startActivity(Intent(this, UserRegisterActivity::class.java))
        }
        login.setOnClickListener {
            when{
                edit_user.text.isNullOrBlank() -> {
                    til_user.error = "请输入正确的用户名"
                }
                edit_password.text.isNullOrBlank() -> {
                    til_user.isErrorEnabled = false
                    til_password.error = "请输入密码"
                }
                else -> {
                    til_user.isErrorEnabled = false
                    til_password.isErrorEnabled = false
                    val user = viewModel.getRepository().getUser(edit_user.text.toString())
                    if (!user.isNullOrEmpty()){
                        if (user[0].password != edit_password.text.toString()){
                            Snackbar.make(edit_password, "用户名或密码错误", Snackbar.LENGTH_SHORT).show()
                        }else{
                            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
                            viewModel.setLoginUser(edit_user.text.toString())
                            startActivity(Intent(this, MainActivity::class.java))
                            finish()
                        }
                    }else{
                        Snackbar.make(edit_password, "用户名或密码错误", Snackbar.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }
}
